package com.ylw.project.handler.impl;

import com.ylw.project.Tools;
import com.ylw.project.constant.ConfigResources;
import com.ylw.project.handler.Handler;
import com.ylw.project.handler.chain.HandlerChain;
import com.ylw.util.Config;

import java.io.File;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 资源文件加载
 */
public class ConfigRsourcesHandler implements Handler {
    @Override
    public Object handler(HandlerChain chain, String filePath) {

        if (check(filePath)) {
            String outputPath = getOutputpath(filePath);
            Tools.copyFile(filePath, outputPath);
        }
        else {
            chain.doHandler(chain.nextHandler());
        }
        return null;
    }

    private boolean check(String filePath) {
        if (ConfigResources.endWith(filePath)) {
            return true;
        }
        return false;
    }


    private String getOutputpath(String path) {

        List<String> webSourceRoot = Config.getPropertValue("project.source.java.root");
        String rootPath = "";
        String relaPath = "";
        for(String ss :webSourceRoot) {
            rootPath = Tools.getOutputProjectRootRealPath(path, ss);
            if("".equals(rootPath)) {
                continue;
            }
            Matcher m = Pattern.compile("\\\\" + ss + "\\\\(.+)").matcher(path);

            if(Tools.isMacOs()) {
                m = Pattern.compile("/" + ss + "/(.+)").matcher(path);
            }
            if (m.find()) {
                relaPath = m.group(1);
                break;
            }
        }
        return rootPath+File.separator +
                Config.getPropertValue("project.output.class.root").get(0)+File.separator+relaPath;
    }


    public static void main(String[] args) {
        String path = "D:\\ideaproject1\\wt_jobs\\src\\com\\ct10000\\business\\wt517\\domain\\Wt_goods_instanceDomain_exp.xml";
        System.out.println(new ConfigRsourcesHandler().getOutputpath(path));
    }
}
